<?php


namespace App\Services;


use App\Models\WxUser;
use App\Tools\JsonTools;
use App\Tools\RedisTools;

class FriendChatService
{
    /**
     * 私聊发送信息
     * @param $data
     * @param $id
     * @return
     */
    public static function friendChat($data,$id){

//        获取自己和好友的IM账号
        $friendIM = WxUser::where('id',$data['receive'])->first();
        $myIM = WxUser::where('id',$id)->first();

        $data['receive'] = $friendIM['im_id'];
        $data['send'] = $myIM['im_id'];

        $IM = new IMServices();

        $res = $IM->openIM($data);

        $mysend = [
            'id'=>$id,
            'nickname'=>$myIM['user_name'],
            'user_image'=>$myIM['user_image'],
            'content'=>[
                'Text'=>$data['content']
            ]
        ];

        $redis = RedisTools::getInstance()->connectRedis();

        $message = $redis->get('message'.$friendIM['id'].$id);
//        如果redis已经存储过聊天记录，删除
        if ($message){
            $redis->del('message'.$friendIM['id'].$id);
        }

        if ($res){
            return $mysend;
        }else {
            return false;
        }

    }

    /**
     * 获取聊天记录
     */

    public static function getMessage($friend,$id){

        $friendIM = WxUser::where('id',$friend)->first();
        $myIM = WxUser::where('id',$id)->first();
        if (!$friendIM){
            return ['data'=>[],'code'=>2022,'msg'=>'好友账号不存在'];
        }
        if (!$myIM){
            return ['data'=>[],'code'=>2022,'msg'=>'账号不存在'];
        }
        $weIM = [
            'my_id'=>$myIM['im_id'],
            'you_id'=>$friendIM['im_id']
        ];

        $IM = new IMServices();

        $res = $IM->searchMessage($weIM);

        $message = [];

//        循环把IM账号替换成ID

        foreach ($res as $v){
            $send = WxUser::where('im_id',$v['From_Account'])->first();

            $message[] = [
                'id'=>$send['id'],
                'nickname'=>$send['user_name'],
                'user_image'=>$send['user_image'],
                'content'=>[
                    'Text'=>$v['MsgBody'][0]['MsgContent']['Text']
                ]
            ];
        }
        $redis = RedisTools::getInstance()->connectRedis();
//        聊天记录存入缓存
        $redis->setex('message'.$friend.$id,86400,json_encode($message,256));
        if ($res){
            return $message;
        }else {
            return false;
        }

    }



    /**
     * 获取自己和好友的IM账号
     */

    public static function userMessage($friend,$id){

        $friendIM = WxUser::where('id',$friend)->first();

        $myIM = WxUser::where('id',$id)->first();

        $IM = new IMServices();

        $userSig = $IM->getSign($myIM['im_id']);

        $data = [
            'myIM'=>$myIM['im_id'],
            'friendIM'=>$friendIM['im_id'],
            'mysig'=>$userSig
        ];

        return $data;
    }
}
